package com.ruoyi.live.base.security;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.live.base.domain.User;
import com.ruoyi.live.base.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class JudgerUserDetailServicceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        IUserService sysUserService = SpringUtils.getBean(IUserService.class);
        User user = sysUserService.findByAccount(account);
        if (user == null) {
            throw new UsernameNotFoundException("该账号不存在");
        }

        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        List<String> permissions = new ArrayList<>();
        permissions.add("judger");
        log.info("用户权限标识 permissions = {}", permissions);
        List<GrantedAuthority> grantedAuthorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new JudgeUser(user.getUserLoginName(), user.getUserPasswordMd5().toString(), grantedAuthorities);
    }
}
